<?php

/*
	Class: WorkflowStatechanges

	About: Author
		Jaybill McCarthy

	About: License
		<http://communit.as/docs/license>


*/
class WorkflowStatechanges extends Workflow_Db_Table{

    protected $_name 	= 'workflow_statechanges';
    protected $_primary = array('role_id','contenttype_id','state_id','target_state_id');

	/* Group: Has No Methods */
	
	function getStateChangesByRole($role_id,$current_state,$contenttype_id){		
		
		$select = $this->select();
		$select->where('role_id = ?',$role_id);
		$select->where('state_id = ?',$current_state);
		$select->where('contenttype_id = ?',$contenttype_id);
		
		$statechanges = $this->fetchAll($select);
		$actions_table = new WorkflowActions();
		$out = array();
		if(count($statechanges) > 0){    
			foreach($statechanges as $statechange){				
				$action = $actions_table->findArray($statechange->action_id);
				
				if(!is_null($action)){
					$out[$statechange->target_state_id] = $action['description'];
				} else {
					$out[$statechange->target_state_id] = $statechange->action_id;
				}
			}
		}
		
		return $out;
		
	}

	function stateChangeMakesContentActive($contenttype_id,$current_state_id,$target_state_id){
		
		$makes_active = false;
		$statechange = $this->fetchRow($this->select()
			->where("contenttype_id = ?",$contenttype_id)
			->where("state_id = ?",$current_state_id)
			->where("target_state_id = ?",$target_state_id)
			);
			
		if(!is_null($statechange)){
			$makes_active = (boolean)$statechange->set_active_true;
		}	
		return $makes_active;
	}

	function isChangeAllowed($content_id,$contenttype_id,$current_state_id,$target_state_id,$username){
		$allowed = false;
		$roles_table = new Roles();
		$user_roles = $roles_table->fetchRolesByUsername($username);
		if(count($user_roles) > 0){
			foreach($user_roles as $user_role){
				$select = $this->select();
				
				$select->where("role_id = ?",$user_role->id)
					->where("contenttype_id = ?",$contenttype_id)
					->where("state_id = ?",$current_state_id)
					->where("target_state_id = ?",$target_state_id);
				
					 
				
				$state_change = $this->fetchRow($select);
				
				if(!is_null($state_change)){
					$allowed = true;
					break;
				}
				
			}
		}
		
		return $allowed;
		
	}

	function getStateChangesByUsername($username,$current_state = "new",$contenttype_id){
				
		$roles_table = new Roles();
		$out = array();
		$user_roles = $roles_table->fetchRolesByUsername($username);
		
		if(count($user_roles) > 0){
			foreach($user_roles as $user_role){
				$out = array_merge($out,$this->getStateChangesByRole($user_role->id,$current_state,$contenttype_id));
			}
		}		
		return $out;		
	}
	
	
	
}


